package MiddleWare

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2021/12/19 - 00:48
 * Desc: <jwt中间件>
 */

import (
	"ali-hr/Services/Auth"
	"ali-hr/Util"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gookit/goutil/dump"
	"gopkg.in/ini.v1"
	"log"
)

// JWTAuth 验证token信息
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 调试模式，跳过中间件
		if IsDebug() == 1 {
			c.Next()
			return
		}

		token := c.Request.Header.Get("token")
		if token == "" {
			Util.FailWithMessage("无权限访问，请先登录！", c)
			c.Abort()
			return
		}

		log.Print("get token: ", token)

		// parseToken 解析token包含的信息
		claims, err := Auth.ParseToken(token)
		fmt.Println("解析token失败，claims：", claims)
		if err != nil {
			Util.FailWithMessage("解析token失效，请重新登录", c)
			//终止程序
			c.Abort()
			return
		}

		// token校验通过，next
		c.Set("claims", claims)
		c.Next()
	}
}

// IsDebug 判断是否为debug模式
func IsDebug() int {
	// 加载配置文件
	appConfig, err := ini.Load("Conf/app.ini")
	if err != nil {
		fmt.Printf("Fail to load file: %v", err)
		return 0
	}

	// 读取配置文件信息
	isDebug, _ := appConfig.Section("debug").Key("debug").Int()
	dump.P("is_debug = ", isDebug)
	return isDebug
}
